const express = require("express")
const wx = express.Router();
const request = require('request')
const nodemailer = require("nodemailer");
const pool = require("../pool/DatabaseConnect")
const { generateToken } = require("../core/utils");
const schedule = require('node-schedule')
/**************************/
// 2.获取邮箱验证码
wx.post("/emailcode", (req, res, next) => {
  //在点击发送验证码时 把邮箱和code存入数据库当中
  let code = Math.floor(Math.random() * 900000) + 100000;
  let obj = req.body;

  let sql = `INSERT INTO email_code value ("${code}","${obj.email}")`;
  pool.query(sql, (err, data) => {
    if (err) {
      next(err);
      return;
    } 
  });
  //简历一个smtp连接
  let transporter = nodemailer.createTransport({
    host: "smtp.163.com",
    secureConnection: true,
    port: 465, 
    auth: {
      user: "alili8029@163.com",
      pass: "JYTQLQCKHBLWTJDW",
    },
  });
  //配置相关参数
  let options = {
    from: "alili8029@163.com",
    to: `${obj.email},alili8029@163.com`,
    //邮箱标题
    subject: "阿力茄汁面有限责任公司",
    //使用模板字符串书写
    html: `<!DOCTYPE html>
 <html>
 <head>
   <meta charset="UTF-8">
   <title>Document</title>
   <style></style>
 </head>
 <body>
   <div class="center">
     <p>尊敬的用户您好:</p>
     <p>欢迎您注册成为阿力租车的会员,您的验证码是${code}。如非本人操作，请忽略本短信。一分钟内有效。</p>
   </div>
 </body>
 </html>`,
  };
  transporter.sendMail(options, function (err, msg) {
    if (err) {
      console.log(err);
    } else {
      res.send(msg);
    }
  });
  // 五分钟后删除该数据
  let startTime = new Date().getTime()
  let endTime =new Date().getTime()+300000
  console.log(startTime,endTime)
  schedule.scheduleJob({start:startTime,end:endTime,rule:' */5 * * * *'},function(){
    let sql = `DELETE ec  FROM email_code  ec WHERE ec.code = ${code} `;
    pool.query(sql,(err,data)=>{
      if(err){
        next(err)
        return
      }
    })
  })


});



wx.post('/wxlogin',(req,res,next)=>{
  let code = req.body.code
  let appid ='wx6bfb0ca459cf2063'
  let secret ='4206dd98ca042ce95ddac230f4beed79'
  let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;

  //获取 session_key和openid
  request(url,function(err,response,body){
    if(!err && response.statusCode == 200){
      // 处理session和openid 
      let data = JSON.parse(body)
      res.send({code:200,data:data,msg:'获取openid成功！'})
    }else{
      res.send({code:412,msg:err})
    }
  })

})
// 判断是否注册过
wx.post('/isregister',(req,res,next)=>{
  let appid = req.body.appid
  let sql = `SELECT * FROM ali_user  a WHERE  a.AUD14 = '${appid}'`
  pool.query(sql,(err,result)=>{
    if(err){
      next(err)
      return
    };
    if(result.length == 0){
      res.send({code:204,msg:'用户未注册！'})
    }else{
      res.send({code:200,msg:'用户已注册，请登录！'})
    }
  })
})
// 注册账户
wx.post('/register',(req,res,next)=>{
  let obj = req.body
  // console.log(obj)
  let code = obj.code || 0
  let openid = obj.openid
  let sqlCode = `SELECT * FROM email_code  ec WHERE ec.code = ${code} `
  pool.query(sqlCode,(err,result)=>{
    if(err){
      next(err)
      return
    }
    if(result.length == 0){
      res.send({code:0,msg:'验证码错误,请核对！'})
      return
    }else{ 
      // 验证码核对成功 将用户注册数据写入数据库
    let sql = `INSERT INTO ali_user(AUD01,AUD03,AUD13,AUD14) VALUES (null,'${obj.email}','${obj.password}','${obj.openid}')`
      pool.query(sql,(err,result)=>{
        if(err){
          next(err)
          return
        }
       if(result.affectedRows!=0){
        const token = generateToken(openid,5)
        res.send({code:200,msg:'注册成功!',token:token})
       }else{
        res.send({code:201,msg:'注册失败！'})
       }
      })
    } 
  })
})

wx.post('/islogin',(req,res,next)=>{
  let email = req.body.email
  let password = req.body.password
  let openid = req.body.openid
  let sql =`SELECT * FROM ali_user  au WHERE au.AUD03 = "${email}" AND au.AUD13 = "${password}"`;

  pool.query(sql,(err,result)=>{
    if(err){
      next(err)
      return
    }
    if(result.length == 0){
      res.send({code:201,msg:'账号密码不正确,请核对！'})
    }else{
      const token = generateToken(openid,5)
      res.send({code:200,msg:'登陆成功！',token:token})
    }
  })

})

// 车辆查询接口
wx.post('/carsearch',(req,res,next)=>{
  let brand = req.body.brand //车辆品牌 0
  let ctype = req.body.ctype //车辆类型 0
  let sql  = `SELECT *  FROM ali_car ac WHERE 1 = 1`;
  // console.log(req.body)
  if(brand !=0){
   sql = sql+` AND ac.AC009 = ${brand} `
  }else if(ctype !=0){
    sql = sql+` AND ac.AC010 = ${ctype} `
  }else if (ctype !=0 && brand!=0){
    sql = sql+` AND ac.AC010 = ${ctype} AND ac.AC009 = ${brand}`
  }else{
    sql = sql
  }
  console.log(sql)
  // return
  pool.query(sql,(err,result)=>{
    if(err){
      next(err)
      return
    }
    // console.log(result)
    if(result.length == 0){
      res.send({code:201,msg:'查询失败！'})
    }else{
      res.send({code:200,msg:'查询成功',data:result})
    }
  })
})
// 根据车辆id获取车辆信息
wx.post('/carid_search',(req,res,next)=>{
  let id = req.body.carid 
  let sql  = `SELECT *  FROM ali_car ac WHERE ac.AC001 = ${id}`;
  // console.log(req.body)

  console.log(sql)
  // return
  pool.query(sql,(err,result)=>{
    if(err){
      next(err)
      return
    }
    // console.log(result)
    if(result.length == 0){
      res.send({code:201,msg:'查询失败！'})
    }else{
      res.send({code:200,msg:'查询成功',data:result})
    }
  })
})

// 订单
wx.post('/send_order',(req,res,next)=>{
  let obj = req.body
  console.log(obj)
  let code = 'AL'+Math.floor(Math.random() * 90000000000) ;
 let sql =`INSERT INTO ali_order(AO001,AO010,AO002,AO003,AO008,AO004,AO005,AO009,AO006,AO007,AO011,AO012,AC001) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)`
  // return
  pool.query(sql,[,code,obj.AO002,obj.AO003,obj.AO008,obj.AO004,obj.AO005,obj.AO009,obj.AO006*1,obj.AO007,obj.AO011,obj.AO012,obj.AC001*1],(err,result)=>{
    if(err){
      next(err)
      return
    }
    if(result.affectedRows!=0){
      res.send({code:200,msg:'订单提交成功!',orderid:code})
    }else{
      res.send({code:201,msg:'订单提交失败！'})
    }
  })
})

// 订单支付
wx.post('/pay_order',(req,res,next)=>{
  schedule.cancelJob()
  let id = req.body.AO010
  let sql = `UPDATE ali_order set AO007 ='0' WHERE AO010 = '${id}' `
  // return
  console.log(sql)
  pool.query(sql,(err,result)=>{
    if(err){
      next(err)
      return
    }
    // console.log(result)
    if(result.affectedRows!=0){
      let sql2 = `SELECT AO001 FROM ali_order WHERE AO010 ='${id}'`
      pool.query(sql2,(err,result)=>{
        if(err){
          next(err)
          return
        }
        res.send({code:200,msg:'支付成功!',list:result[0]})
      })
     
    }else{
      res.send({code:201,msg:'支付失败!'})
    }
  })
})
// 门店查询
wx.post('/stores_search',(req,res,next)=>{

  sql ='SELECT * FROM ali_map'
  pool.query(sql,(err,result)=>{
    if(err){
      next(err)
      return
    }
    if(result.length == 0){
      res.send({code:201,msg:'查询失败！'})
    }else{
      res.send({code:200,msg:'查询成功',data:result})
    }
  })
})
//取消订单支付 
wx.post('/cancel_pay_order',(req,res,next)=>{
  // 起始时间是0s 结束时间是十五分钟后
  // 在这期间 每一秒执行一次
  let orderid = req.body.AO010
  let startTime = new Date().getTime()
  let endTime =new Date().getTime()+900001
  res.send({code:1,msg:'等待用户支付！'})
  schedule.scheduleJob({start:startTime,end:endTime,rule:'*/15 * * * *'},function(){
    let sql = `DELETE  FROM ali_order WHERE AO010 = ?`;
    pool.query(sql,orderid,(err,result)=>{
      if(err){
        next(err)
        return
      }
    })

  })
})
// 订单状态查询

wx.post('/search_all_order',(req,res,next)=>{
  let AO007 = req.body.AO007
  let sql = 'SELECT * FROM ali_order WHERE AO007 = ?'
  pool.query(sql,AO007,(err,result)=>{
    if(err){
      next(err)
      return
    }
  
    if(result.length == 0){
      res.send({code:200,data:result})
    }else{
      res.send({code:200,data:result})
    }
  })
})
// 新增租车常用联系人
wx.post('/peoples_add',(req,res,next)=>{
  let UCR02 =req.body.UCR02 
  let UCR03 =req.body.UCR03
  let UCR04 =req.body.UCR04
  let UCR05 =req.body.UCR05
  let UCR06 =req.body.UCR06
  let sql2 = 'select * from user_car_rental where ucr05 = ? '
  pool.query(sql2,UCR05,(err,result)=>{
    if(err){
      next(err)
      return
    }
    if(result.length == 0){
      let sql = 'INSERT INTO  user_car_rental value (?,?,?,?,?,?)'
      pool.query(sql,[null,UCR02,UCR03,UCR04,UCR05,UCR06],(err,result)=>{
        if(err){
          next(err)
          return
        }
        if(result.affectedRows!=0){
          res.send({code:200,msg:'新增成功！'})
        }else{
          res.send({code:201,msg:'新增失败！'})
        }
      })
    }else{
      res.send({code:201,msg:'身份证号码重复！'})
    }
  })




})

// 取消订单
wx.post('/cancel_order',(req,res,next)=>{
 let AO010 = req.body.AO010
 let sql = 'UPDATE ali_order set AO007 ="4" WHERE AO010 =?' 
 pool.query(sql,AO010,(err,result)=>{
  if(err){
    next(err)
    return
  }
  if(result.affectedRows!=0){
    res.send({code:200,msg:'订单取消成功!'})
  }else{
    res.send({code:201,msg:'订单取消失败！'})
  }
 })

})

wx.post('/search_peoples',(req,res,next)=>{

  let sql = 'SELECT * FROM user_car_rental'
  pool.query(sql,(err,result)=>{
    if(err){
      next(err)
      return
    }
    if(result.length == 0){
      res.send({code:201,msg:'数据为空！',data:result})
    }else{
      res.send({code:200,data:result})
    }
  })
})


/**************************/
module.exports = wx; 